package com.huayun.plugin.materialLibrary.service;
import com.huayun.plugin.materialLibrary.dao.MaterialLibraryRepository;
import com.huayun.plugin.materialLibrary.domain.MaterialLibrary;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

;

@Service
public class MaterialLibraryService {
    @Autowired
    private final MaterialLibraryRepository materialLibraryRepository;
    private final Logger logger = LoggerFactory.getLogger(MaterialLibraryService.class);

    public MaterialLibraryService(MaterialLibraryRepository materialLibraryRepository) {
        this.materialLibraryRepository = materialLibraryRepository;
    }

    public void parseExcelAndSave(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();//获取文件的输入流，用流的方式进行解析；
        Workbook workbook = new XSSFWorkbook(inputStream);//通过Workbook类可以对excel文件进行读取和写入
        Sheet sheet = workbook.getSheetAt(0);//通过Workbook类获取第一张sheet表
        Iterator<Row> rowIterator = sheet.iterator();
        if (rowIterator.hasNext()){
            Row headerRow = rowIterator.next();
            Map<String,String> columnMap = getHheaderColumnMap(headerRow);
            while (rowIterator.hasNext()){
                MaterialLibrary materialLibrary = new MaterialLibrary();
                Row row = rowIterator.next();
                Iterator<Cell> cellIterator = row.cellIterator();
                int cellIndex = 0;
                while (cellIterator.hasNext()){
                    Cell cell = cellIterator.next();
                    String columnKey = getColumnNameByIndex(sheet,cellIndex);
                    if (columnMap.containsKey(columnKey)){
                        String mongoFieldName  = columnMap.get(columnKey);//获取在mongodb表中的名字
                        switch (mongoFieldName) {
                            case "_id":
                                materialLibrary.setId(cell.getStringCellValue());
                                break;
                            case "number":
                                materialLibrary.setNumber(cell.getStringCellValue());
                                break;
                            case "name":
                                materialLibrary.setName(cell.getStringCellValue());
                                break;
                            case "level":
                                materialLibrary.setLevel(cell.getStringCellValue());
                                break;
                            case "area":
                                materialLibrary.setArea(cell.getStringCellValue());
                                break;
                            case "density":
                                materialLibrary.setDensity(cell.getStringCellValue());
                                break;
                            case "standard":
                                materialLibrary.setStandard(cell.getStringCellValue());
                                break;
                            case "unit":
                                materialLibrary.setUnit(cell.getStringCellValue());
                                break;
                            case "layer":
                                materialLibrary.setLayer(cell.getNumericCellValue());
                                break;
                        }
                    };
                    cellIndex++;
                }
                materialLibraryRepository.save(materialLibrary);
            }
        }
    }
    //根据表头列名，设置对应的数据表字段名
    private Map<String,String> getHheaderColumnMap(Row headerRow){
        Map<String,String> columnMap = new HashMap<>();
        Iterator<Cell> cellIterator = headerRow.cellIterator();
        while (cellIterator.hasNext()){
            Cell cell = cellIterator.next();
            String columnName = cell.getStringCellValue().toLowerCase();
            switch (columnName){
                case "ID":
                    columnMap.put(columnName,"_id");
                    break;
                case "材料编号":
                    columnMap.put(columnName,"number");
                    break;
                case "名称":
                    columnMap.put(columnName,"name");
                    break;
                case "牌号或者型类级":
                    columnMap.put(columnName,"level");
                    break;
                case "毛料尺寸":
                    columnMap.put(columnName,"area");
                    break;
                case "面密度":
                    columnMap.put(columnName,"density");
                    break;
                case "单位":
                    columnMap.put(columnName,"unit");
                    break;
                case "材料规范":
                    columnMap.put(columnName,"standard");
                    break;
            }
        }
        return columnMap;
    }
    //根据根据当前表格下标获取所在列的表头名
    private String getColumnNameByIndex(Sheet sheet,int index){
        Row headerRow = sheet.getRow(0);//获取表头行；
        if (headerRow != null && headerRow.getCell(index) != null) {
            Cell cell = headerRow.getCell(index);
            return cell.getStringCellValue().toLowerCase();
        }
        return "";
    }
    public List<MaterialLibrary> getMaterialLibraryData(){
        List<MaterialLibrary> materialLibraryList = materialLibraryRepository.findAll();
        return materialLibraryList;
    }

    public List<MaterialLibrary> addMaterialLibraryItem(String number, String name,String level,String area,String density,String standard,String unit,Number layer){
        MaterialLibrary materialLibrary = new MaterialLibrary();
        materialLibrary.setNumber(number);
        materialLibrary.setName(name);
        materialLibrary.setLevel(level);
        materialLibrary.setArea(area);
        materialLibrary.setDensity(density);
        materialLibrary.setStandard(standard);
        materialLibrary.setUnit(unit);
        materialLibrary.setLayer(layer);
        materialLibraryRepository.insert(materialLibrary);
        List<MaterialLibrary> materialLibraryList = materialLibraryRepository.findAll();
        return materialLibraryList;
    }
    public List<MaterialLibrary> deleteMaterialLibraryItem(String id){
        materialLibraryRepository.deleteById(id);
        List<MaterialLibrary> materialLibraryList = materialLibraryRepository.findAll();
        return materialLibraryList;
    }
    public List<MaterialLibrary> updateMaterialLibraryItem(String id, String number, String name,String level,String area,String density,String standard,String unit, Number layer){
        Optional<MaterialLibrary> materialItem = materialLibraryRepository.findById(id);
        if(materialItem.isPresent()){
            MaterialLibrary materialLibraryItemInfo = materialItem.get();
            materialLibraryItemInfo.setNumber(number);
            materialLibraryItemInfo.setName(name);
            materialLibraryItemInfo.setLevel(level);
            materialLibraryItemInfo.setArea(area);
            materialLibraryItemInfo.setDensity(density);
            materialLibraryItemInfo.setStandard(standard);
            materialLibraryItemInfo.setUnit(unit);
            materialLibraryItemInfo.setLayer(layer);
            materialLibraryRepository.save(materialLibraryItemInfo);
        }
        List<MaterialLibrary> materialLibraryList = materialLibraryRepository.findAll();
        return materialLibraryList;
    }
    public List<MaterialLibrary> queryMaterialLibraryList(String keyWords){
        List<MaterialLibrary> numberContains = materialLibraryRepository.findByNumberContaining(keyWords);
        List<MaterialLibrary> nameContains = materialLibraryRepository.findByNameContaining(keyWords);
        List<MaterialLibrary> levelContains = materialLibraryRepository.findByLevelContaining(keyWords);
        List<MaterialLibrary> areaContains = materialLibraryRepository.findByAreaContaining(keyWords);
        List<MaterialLibrary> densityContains = materialLibraryRepository.findByDensityContaining(keyWords);
        List<MaterialLibrary> standardContains = materialLibraryRepository.findByStandardContaining(keyWords);
        List<MaterialLibrary> unitContains = materialLibraryRepository.findByUnitContaining(keyWords);
        List<MaterialLibrary> materialLibraryList = new ArrayList<>();
        materialLibraryList.addAll(numberContains);
        materialLibraryList.addAll(nameContains);
        materialLibraryList.addAll(levelContains);
        materialLibraryList.addAll(areaContains);
        materialLibraryList.addAll(densityContains);
        materialLibraryList.addAll(standardContains);
        materialLibraryList.addAll(unitContains);
        //根据字段进行模糊查询
        List<MaterialLibrary> result = materialLibraryList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toMap(
                                MaterialLibrary::getId,
                                material -> material,
                                (existing, replacement) -> existing
                        ),
                        map -> new ArrayList<>(map.values())
                ));
        List<MaterialLibrary> sortedList = result.stream()
                .sorted(Comparator.comparing(MaterialLibrary::getId))
                .collect(Collectors.toList());


        return sortedList;
    }
}
